package com.yaorange.certificate.service;

import com.yaorange.certificate.utils.QiniuUtils;
import com.yaorange.common.exception.ServiceException;
import com.yaorange.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2025/1/17
 */
@Slf4j
@Service
public class CommonService {
    @Autowired
    private QiniuUtils qiniuUtils;

    /*public String uploadFile(MultipartFile multipartFile) {
        //1.将文件保存到本地硬盘,保存到d://static/images/目录下
        //1212.线程池原理.png
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
        //skjkx-xx9d.png
        String uuidName = UUID.fastUUID() + "." + suffix;
        File dest = new File("d://static/images/"+uuidName);
        //判断文件夹是否存在,不存在需要创建
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            log.error("保存到硬盘失败", e);
            throw new ServiceException("文件上传失败");
        }
        //2.反应给浏览器一个可访问的地址 http://localhost:8080/images/图片名字
        return "http://localhost:8080/images/"+uuidName;
    }*/

    public String uploadFile(MultipartFile multipartFile) {
        //1.将文件保存到本地硬盘,保存到d://static/images/目录下
        //1212.线程池原理.png
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
        //skjkx-xx9d.png
        String uuidName = UUID.fastUUID() + "." + suffix;
        try {
           //调用七牛云sdk上传文件
            qiniuUtils.uploadFile(multipartFile.getBytes(),uuidName);
        } catch (IOException e) {
            log.error("保存到硬盘失败", e);
            throw new ServiceException("文件上传失败");
        }
        //2.反应给浏览器一个可访问的地址 http://localhost:8080/images/图片名字
        //为了给七牛云一点时间，隔1秒再相应给客户端
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "http://sq7xweid0.hn-bkt.clouddn.com/"+uuidName;
    }
}
